<?php

    class Pages_Controller extends Application {
        
        function setup()
        {
            $this->actions = array('index','add','templates','delete','edit_meta',
                                   'show_editable_regions','search_pages','reorder',
                                   'edit_content_area','permissions','list_of_pages',
                                   'related_pages','js_list');
            $this->use_layout('admin_layout.php');
            $this->before_filter('is_logged_in');
            $this->before_filter('has_access');
            use_model('pages','page_content');
			
			// subnav
			$subnav = array();
			$subnav['All Pages'] = array('controller'=>'admin/pages' );
			if (has_access_to('Pages::Modify Templates'))
			{
				$subnav['Templates'] = array('controller'=>'admin/pages' ,'action'=>'templates');
			}
			
			// custom fields
			if (has_access_to('Custom Fields::Manage Fields'))
			{
				$subnav['Custom Fields'] = array('controller'=>'admin/custom_fields');
			}
			$this->assign('subnav',$subnav);
        }

        function has_access()
        {
            if (!has_access_to('Pages::Access Pages')) {
                flash('error','Sorry but you do not have access to the Pages tool');
                $this->redirect_to(array('controller'=>'admin/dashboard' ));            
            }
        }
        
        function add()
        {
            if ( $this->is_post() )
		    {
		        $pages = new Pages();
		        // add new page
		        if ( has_access_to('Pages::Add Pages') && $pages->update_fields($_POST['pages']) )
		        {
		            flash('notice','Page Saved');
		            $goto = rawurlencode('pages[id]').'='.$pages->get('id');
		            $this->redirect_to(array('controller'=>'admin/pages' ,'action'=>'index?'.$goto));
		        } else {
		            flash('error','Error adding page.');
		            $this->redirect_to(array('controller'=>'admin/pages' ,'action'=>'index'));
		        }
		        return;
		    } 
		    $this->render(array('nothing'=>true));
        }
        
		function index() 
		{
		    $pages = new Pages();
		    $this->assign_ref('pages',$pages);			    		    
		    
		    if ( isset($_POST['action']) 
		        && $_POST['action'] == 'edit_page' 
		        && has_access_to('Pages::Edit Pages'))
		    {
		        $id = (int) $_POST['pages']['id'];
		        if ( $pages->load($id) && $pages->update_fields($_POST['pages']) )
		        {
		            flash('notice','Page Saved');
		            $goto = rawurlencode('pages[id]').'='.$pages->get('id');
		            $this->redirect_to(array('controller'=>'admin/pages' ,'action'=>'index?'.$goto));
		        } else {
		            flash('error','Error saving page');
		        }
		    }
		    
		    // get id to load
		    $id = isset($id) ? $id : (int) @$_REQUEST['pages']['id'];
		    if ( isset($id) )
		    {		        
		        if ( $pages->load($id) )
		        {		            		        		        
    		        // load all users and pages permission crap
    		        use_model('users');
    		        $users = new Users();
    		        $this->assign_ref('users',$users);
    		        
    		        // get available custom fields
    		        use_model('custom_fields');
    		        $cf = new custom_fields();
    		        $this->assign('custom_fields', $cf->assoc());
		        
    		        // check if admin is accessing page and bypass any page permissions
    		        // if its just a normal user check the page permissions
    		        if ( !has_access_to('Admin::Access Admin') 
    		             && $has_permissions = $pages->get('has_permissions') )
    		        {
    		            if ( !in_array($_SESSION['user_id'], array_keys($page_users)) )
                        {
                            flash('error','You do not have permission to edit '.$pages->get('title'));
                            $pages->unload(); // clear out any page values
                            $this->assign('page',array());
                        }
    		        }
		        }		                        		        		        
		    }
		}		
		
		// should render the page with the regions highlighted
		function show_editable_regions()
		{
		    // get page by id
		    if ( !empty($_GET['id']) )
		    {
		        $pages = new Pages();
		        $id    = (int) $_GET['id'];
		        if ( $pages->load($id) )
		        {
		            $this->assign('page',$pages);
		            $this->assign('admin_edit',true);
		            
		            // render page
	                if ( $pages->get('disable_default_layout') )
		            {
		                $this->use_layout(false);
		            } else {
		                $this->use_layout('application.php');
		            }

		            $this->render(array('template'=>'templates/'.$pages->get('template_file')));
		        } else {
		            $this->render(array('inline'=>'page failed to load.'));
		        }
		    }
		}
		
		// output for the tiny mce browser
		function js_list()
		{
		    $pages = new Pages();
		    $this->assign_ref('pages',$pages);
		    
		    use_model('news');
		    $news = new News();
		    $this->assign_ref('news',$news);
		    
		    $this->use_layout(false);
		}
		
		
		// editing of a singular content area
		function edit_content_area()
		{
		    $this->use_layout(false);
		    if ( isset($_GET['action']) && $_GET['action'] == 'edit_region' )
		    {		        
		        $page_content = new Page_Content();
		        if ( $page_content->load('section=? and page_id=?', array($_GET['section'], (int)$_GET['page_id'])) )
		        {
		            $this->assign_ref('content',$page_content);
		        }
		    }
		    
		    if ( isset($_POST['action']) 
		          && $_POST['action'] == 'edit_content' 
		          && has_access_to('Pages::Edit Pages') )
		    {
		        if ( isset($_POST['cancel']) )
		        {		            
		            $this->redirect_to(array('controller'=>'admin/pages' ,'action'=>'show_editable_regions?id='.$_POST['page_id']));
		        }
		        
		        $id = (int) $_POST['id'];
		        $page_content = new Page_Content();
		        $page_content->load($id);
		        $page_content->update_fields($_POST);		      
		        
		        $this->redirect_to(array('controller'=>'admin/pages' ,
		                                 'action'=>'show_editable_regions?id='.$_POST['page_id']));
		    }
		    
		}
		
		function edit_meta()
		{
		    if ( isset($_POST['action']) 
		         && $_POST['action'] == 'edit_meta'  
		         && has_access_to('Pages::Edit Pages') )
		    {
		        $pages = new Pages();
		        $id = (int) $_POST['pages']['id'];
		        if ( $pages->load($id) && $pages->update_fields($_POST['pages']) )
		        {
		            $this->render( array('inline'=>'Meta Information Saved') );
		            return;
		        }
		    }
		    $this->redirect_to('index');
		}
		
		// delete a page
		function delete()
		{
		    if ( isset($_POST['action']) 
		        && $_POST['action'] == 'delete' 
		        && !empty($_POST['id']) 
		        && has_access_to('Pages::Delete Pages') )
		    {
		        $pages = new Pages();
		        $id = (int) $_POST['id'];
		        if ( $pages->load($id) && $pages->delete() )
		        {
		            flash('notice','Page Deleted');
		        } else {
		            flash('error','Page has been deleted. If it had children pages, they have been moved to the deleted parent parents page. Sorry if this is confusing.');
		        }
		    }
		    $this->redirect_to('index');
		}
		
		// used in the autocomplete search box
		function search_pages()
		{
		    if ($this->is_get() && !empty($_GET['title']))
		    {
		        // find id by title
		        $title = $_GET['title'];
		        $pages = new Pages();
		        if ($pages->load('title=?',array($title))) {
		            $goto = rawurlencode('pages[id]').'='.$pages->get('id');
    	            $this->redirect_to(array('controller'=>'admin/pages' ,'action'=>'index?'.$goto));
		        } else {
		            flash('error','Page not found');
		            $this->redirect_to('index');
		            return;
		        }
		    } 
		    
		    if ($this->is_post() && !empty($_POST['title'])) {
		        $pages = new Pages();
    		    $found_pages = $pages->find_rows( array(
    		                                'conditions'=>array('lower(title) like ?', '%'.strtolower($_POST['title']).'%'),
    		                                'order' =>'title asc',
    		                                'limit'=>8,
    		                                'fields'=>'title'
    		                                ) );

    		    $this->assign('found_pages',$found_pages);
    		    $this->render(array('partial'=>'_found_pages.php'));
    		    return;
		    }
		    
		    $this->render(array('nothing'=>true));
		}

        // edit templates found in views folder?
		// views/pages/templates ?
		function templates()
		{
		    if (!has_access_to('Pages::Modify Templates')) {
		        flash('error','You do not have access to modify the templates');
		        $this->redirect_to('index');
		    }
		    $pages = new Pages();
		    $this->assign_ref('pages',$pages);
		    
		    // remove template
		    if ($this->is_post()
		        && $_POST['action'] == 'delete_template') {
		        if ($pages->remove_template($_POST['template_file'])) {
		            flash('notice','Template Removed');
		        } else {
		            flash('error','Template not deleted');
		        }
		    }
		    
		    // add template
		    if ($this->is_post() 
		        && $_POST['action'] == 'add_template') {
		      if ($pages->add_template($_POST)) {
		          flash('notice', 'Template Created');
		      } else {
		          flash('error','Template creation failed');
		          $this->assign('errors', $pages->errors_to_string());
		      }
		    }
		    
		    // write template
		    if ( $this->is_post() 
		         && $_POST['action'] == 'edit_template')
		    {
		        if ($pages->write_to_template($_POST))
		        {
		            flash('notice','Template saved');
		        } else {
		            flash('error','Template could not be saved!');
		        }
		        
		        if ($_POST['commit'] == "Save and Finished") {
	                $this->redirect_to('templates');
		        } else {
		            $this->redirect_to('templates?template_name='.rawurlencode(strip_tags($_POST['template_name'])));
		        }
		    }
		    
		    // show code for given template
		    if ( !empty($_GET['template_name']) )
		    {		        
		        $this->assign('is_writable',$pages->template_is_writable($_GET['template_name']));
		        $this->assign('template_code',$pages->get_template_code($_GET['template_name']));	        
		        $this->assign('template_name',$_GET['template_name']);
		        $this->render(array('template'=>'edit_template.php'));
		    }
		    
		    $this->assign('templates',$pages->get_templates(true));		    
		}
		
		function permissions()
		{
		    if (!has_access_to('Pages::Lock Pages')) {
                flash('error','Sorry but you do not have access');
                $this->redirect_to('index');            
            }
            
            if ( isset($_POST['pages']['id']) )
            {
                $pages = new Pages();
                if ( $pages->page_permissions( (int) $_POST['pages']['id'], $_POST['users']) )
                {
                    $this->render(array('inline'=>'Success: Permissions Updated'));
                } else {
                    $this->render(array('inline'=>'Not updated'));
                }
            }
            
		}
		
		function list_of_pages()
		{
		    $this->use_layout(false);
		    $pages = new Pages();
		    $list = $pages->get_pages_for_js();
		    $this->assign('list',$list);
		}
		
		function reorder() 
		{
		    $pages = new Pages();
		    if ( $this->is_ajax_request() )
		    {
		        $pages->reorder_pages($_POST['pages']);
		        $this->render( array('inline'=>'Order Saved') );
		        return;
		    }		    
		    $this->redirect_to('index');
		}
		
		function related_pages()
		{
		    use_model('related_pages');
		    $pages = new Related_Pages();
		    if ( $this->is_ajax_request() && isset($_POST['pages']['id']) )
		    {
		        $pages->save_related((int) $_POST['pages']['id'], $_POST['related_pages']);
		        $this->render( array('inline'=>'Related Pages Saved') );
		        return;
		    }		    
		    $this->redirect_to('index');
		}
		
    }

?>